package com.yxinmiracle.search.service;

import com.alibaba.fastjson.JSON;
import com.yxinmiracle.search.pojo.SkuInfo;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * // 1. 获取非高亮的数据
   // 2. 获取高亮的数据
   // 3. 替换
 * @version 1.0
 * @author： YxinMiracle
 * @date： 2021-08-13 17:05
 */

public class SearchResultMapperImpl implements  SearchResultMapper {
    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
        List<T> content = new ArrayList<>();

        SearchHits hits = searchResponse.getHits();
        if(hits==null || hits.getTotalHits()<=0){ // 判断有无数据
            return new AggregatedPageImpl<T>(content);
        }
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString(); // 获取的是pojo 没有高亮的
            SkuInfo skuInfo = JSON.parseObject(sourceAsString, SkuInfo.class);

            Map<String, HighlightField> highlightFields = hit.getHighlightFields(); // 获取高亮数据

            if (highlightFields!=null && highlightFields.get("name") !=null && highlightFields.get("name").getFragments() != null && highlightFields.get("name").getFragments().length>0){
                HighlightField highlightField = highlightFields.get("name");
                Text[] fragments = highlightField.getFragments();
                StringBuffer sb = new StringBuffer();
                for (Text fragment : fragments) {
                    String string = fragment.string();
                    sb.append(string);
                }
                skuInfo.setName(sb.toString());
            }
            content.add((T) skuInfo);
        }

        long totalHits = searchResponse.getHits().getTotalHits();
        Aggregations aggregations = searchResponse.getAggregations();
        String scrollID = searchResponse.getScrollId();
        return new AggregatedPageImpl<T>(content,pageable,totalHits,aggregations,scrollID);
    }
}
